package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.pm.ActivityInfo;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.video.JZMediaIjkplayer;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.CommentRvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.CommentInfo;
import com.ycsj.goldmedalnewconcept.common.bean.LivingInfo;
import com.ycsj.goldmedalnewconcept.common.bean.UpdateResInfo;
import com.ycsj.goldmedalnewconcept.common.sharesdk.OneKeyShareCallback;
import com.ycsj.goldmedalnewconcept.common.sharesdk.ShareManager;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import cn.sharesdk.framework.Platform;
import okhttp3.Call;

/**
 * 直播界面
 * Created by Administrator on 2019/2/26 0026.
 */

public class LivingActivity extends BaseActivity implements View.OnLayoutChangeListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.rl_content)
    RelativeLayout rlContent;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    //Activity最外层的Layout视图
    @BindView(R.id.ll_main)
    View activityRootView;

    //播放器控件
    private JZVideoPlayerStandard player;

    //评论列表的数据源
    private List<CommentInfo.DataBean.CommentBean> oldDatas;

    //评论列表的适配器
    private CommentRvAdapter adapter;


    //头布局
    private View headView;

    //空视图
    private View emptyView;


    //头布局的
    private EditText etInput;
    private TextView tvNum;
    private Button btSend;

    //屏幕高度
    private int screenHeight = 0;

    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    //页面的直播对象
    private LivingInfo.DataBean info;

    private String logo;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_living;
    }

    @Override
    protected void init() {

        //初始化状态栏
        initStateBar();

        //初始化标题栏
        initIntent();

        //设置列表
        initRv();

        //请求服务器
        http(BqaManager.NORML);
    }

    /**
     * 获取传递的直播对象
     */
    private void initIntent() {

        info = (LivingInfo.DataBean) getIntent().getSerializableExtra("data");

        if (info != null) {
            tvTitle.setText(info.getTITLE());
        } else {
            tvTitle.setText("直 播 课");
        }


        lvEdit.setVisibility(View.VISIBLE);
        lvEdit.setImageResource(R.drawable.base_share);

        //获取屏幕高度
        screenHeight = ScreenUtils.getScreenHeight(this);

        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;

        if (TextUtils.isEmpty(AccountUtils.getLogo(this))) {
            logo = "http://139.129.57.83:8080/Appandroid/applogo.png";
        } else {
            logo = AccountUtils.getLogo(this);
        }
    }

    /**
     * 初始化播放器
     */
    private void initPlayer(CommentInfo.DataBean dataBean) {
        //切换播放引擎为ijk
        JZVideoPlayer.setMediaInterface(new JZMediaIjkplayer());

        //设置缩略图的显示方式
        player.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        //设置播放的缩略图
        ImageUtil.displayImage(this, player.thumbImageView, dataBean.getIMG_URL2(), R.drawable.ic_default_image);

        //设置不显示返回键
        player.backButton.setVisibility(View.GONE);

        //设置不显示电量
        player.batteryLevel.setVisibility(View.GONE);

        //设置直播的推流地址
        player.setUp(dataBean.getPROTOCOL_URL1(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, dataBean.getTITLE());

        //进入直接播放
        player.startVideo();

        //设置播放模式 JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP,VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT(铺满播放),JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL(原始播放)
        JZVideoPlayer.setVideoImageDisplayType(JZVideoPlayer.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);

        //这两句是设置点击全屏后直接横屏播放
        JZVideoPlayer.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        JZVideoPlayer.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    /**
     * 设置列表
     */
    private void initRv() {
        headView = View.inflate(this, R.layout.teacher_headview_comment, null);
        etInput = headView.findViewById(R.id.et_edit);
        tvNum = headView.findViewById(R.id.tv_num);
        player = headView.findViewById(R.id.player);
        btSend = headView.findViewById(R.id.bt_send);

        //发送按钮的点击事件
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = etInput.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    UiUtils.Toast("未输入评论内容", false);
                    return;
                } else {
                    //请求服务器,上传评论内容,成功后更新评论的列表适配器,同时让RecyclerView复原到指定位置,清空输入框的内容
                    doSendCommentAction(content);
                }
            }
        });

        etInput.setFilters(new InputFilter[]{new MaxTextLengthFilter(101)});
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = etInput.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    if (content.length() > 101) {
                        tvNum.setText("100/100");
                    } else {
                        tvNum.setText(content.length() + "/100");
                    }
                }
            }
        });

        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        adapter = new CommentRvAdapter(this, R.layout.teacher_comment, oldDatas);
        adapter.addHeaderView(headView);
    }


    /**
     * 发送评论的操作
     */
    private void doSendCommentAction(String content) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "3");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "2");
        map.put("username", AccountUtils.getName(this));
        map.put("content", content);
        map.put("videoid", info.getROW_ID() + "");

        HttpUtils.post(HttpAddress.SENDCOMMENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rv.smoothScrollToPosition(0);
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    UpdateResInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, UpdateResInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("评论成功", false);
                            //刷新页面数据
                            http(BqaManager.PULLREFRESH);
                            //清空
                            etInput.setText("");
                            tvNum.setText("0/100");
                            rv.smoothScrollToPosition(0);
                        } else {
                            rv.smoothScrollToPosition(0);
                            UiUtils.Toast("评论成功,返回错误码:" + info.getState(), false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }


    /**
     * 请求服务器数据的方法
     *
     * @param method
     */
    private void http(final int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");
        map.put("rowid", info.getROW_ID() + "");

        HttpUtils.post(HttpAddress.LEAVEING, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, null, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    CommentInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, CommentInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info && "200".equals(info.getState())) {
                        //返回成功
                        CommentInfo.DataBean dataBean = info.getData();
                        if (null != dataBean) {

                            if (method == BqaManager.NORML) {
                                //设置播放器
                                initPlayer(dataBean);
                            }

                            List<CommentInfo.DataBean.CommentBean> newDatas = dataBean.getComment();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    //设置评论列表
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, LivingActivity.this, adapter, rv);
                                } else {
                                    BqaManager.updateRvBySmf(method, null, rv, oldDatas, newDatas, adapter);
                                    adapter.setEnableLoadMore(false);
                                }
                            }
                        }
                    } else {
                        UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                        Log.i("test", Constants.ERRORSTATE + info.getState());
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 加入对根据局的管理监听,主要是解决软键盘弹出和关闭的监听状态
     */
    @Override
    protected void onResume() {
        super.onResume();

        //添加layout大小发生改变监听器
        activityRootView.addOnLayoutChangeListener(this);
    }


    /**
     * 监听软键盘
     */
    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            //将RecyclerView往上滚动一定距离
            if (oldDatas != null && oldDatas.size() > 0) {
                rv.smoothScrollToPosition(1);
            }
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            rv.smoothScrollToPosition(0);
        }
    }


    /**
     * 分享直播
     */
    private void Share() {

        //分享地址
        String shareUrl = HttpAddress.UPDATE_URL + "JPXB/sharePage/pages/JPXGN_JPXB/videoLive/videoLive.html?vid="
                + info.getROW_ID() + "&appType=2&normal=2";

        //图标
        String imgUrl = logo;

        //分享标题
        String title = info.getTITLE();
        String content = "";
        if (TextUtils.isEmpty(AccountUtils.getSchoolName(this))) {
            content = AccountUtils.getName(this) + "邀您收听直播\n时间:" + info.getBEGIN_TIME();
        } else {
            content = AccountUtils.getSchoolName(this) + "邀您收听直播\n时间:" + info.getBEGIN_TIME();
        }

        ShareManager.newInstance().showOneShare(this, title, shareUrl,
                content, imgUrl, shareUrl, new OneKeyShareCallback() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        Log.i("test", "分享成功");
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {
                        Log.i("test", "分享失败");
                    }

                    @Override
                    public void onCancel(Platform platform, int i) {
                        Log.i("test", "取消分享");
                    }
                });
    }


    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        JZVideoPlayer.releaseAllVideos();

        //横屏还原时恢复传感器的值
        JZVideoPlayer.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
        JZVideoPlayer.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    @Override
    protected void onDestroy() {
        JZVideoPlayer.releaseAllVideos();
        super.onDestroy();
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //分享
                Share();
                break;
        }
    }
}
